﻿using GamFi.API.Application.Contracts.Chat.GetMessages;
using GamFi.API.Application.Interfaces;
using GamFi.API.Application.Models;
using GamFi.API.Domain.Entities;
using MediatR;
using Microsoft.EntityFrameworkCore;
using MongoDB.Bson;
using MongoDB.Driver;

namespace GamFi.API.Application.Features.Queries.Chat.GetMessages;

public class GetMessagesQueryHandler(IDbContext dbContext, IMongoDatabase database)
    : IRequestHandler<GetMessagesQuery, GetMessagesResponse>
{
    public async Task<GetMessagesResponse> Handle(GetMessagesQuery request, CancellationToken cancellationToken)
    {
        var messagesCollection = database.GetCollection<Message>("Messages");
        var messagesFromDb = await messagesCollection.Find(new BsonDocument()).ToListAsync(cancellationToken);

        var users = await dbContext.Users.Include(u => u.UserInfo).ToListAsync(cancellationToken);
        var userDict = users.ToDictionary(u => u.UserInfo.Id);

        var oldMessages = messagesFromDb.Select(m => new SendMessageDto
        {
            Id = Guid.Parse(m.Id),
            Text = m.TextMessage,
            WhoSentId =  Guid.Parse(m.CreatedBy),
            SenderName = userDict[Guid.Parse(m.CreatedBy)].UserName ?? "Unknown",
            SenderImageId = userDict[Guid.Parse(m.CreatedBy)].UserInfo.ImageId,
        }).ToList();

        return new GetMessagesResponse { Messages = oldMessages };
    }
}